package org.lightmtv.request;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Locale;

import org.lightcommons.util.StringUtils;
import org.lightcommons.web.HttpHeaders;

public abstract class AbstractRequest implements Request {
	
	@SuppressWarnings("unchecked")
	public Locale[] getLocales() {
		String acceptLanguage = getHeader(HttpHeaders.Accept_Language);
		if(acceptLanguage==null)
			return new Locale[0];
		Enumeration<Locale> locales = AcceptLanguage.getLocales(acceptLanguage);
		List<Locale> localeList = new ArrayList<Locale>();
		while(locales.hasMoreElements()){
			localeList.add(locales.nextElement());
		}
		return localeList.toArray(new Locale[localeList.size()]);
	}
	
	public Locale getBestLocaleIn(Locale[] avariableLocales) {
		for(Locale la:getLocales()){
			for(Locale lb: avariableLocales){
				if(lb.equals(la) || (!StringUtils.hasLength(la.getCountry()) && la.getLanguage().equals(lb.getLanguage())) )
						return lb;
			}
		}
		return avariableLocales[0];
	}
	
	public String getReferer() {
		return getHeaders().get(HttpHeaders.Referer);
	}
	
	public String getHeader(String name) {
		return getHeaders().get(name);
	}
}
